<template>
  <div class="user-manager">
    <div class="search">
      <el-input placeholder="请输入用户名、登录名" v-model="state.searchValue"></el-input>
      <el-button class="search-btn" type="primary" :icon="Search" @click="searchData">搜索</el-button>
      <el-button class="search-btn" type="primary" :icon="Plus" @click="handleAdd">添加</el-button>
    </div>

    <div class="table-con">
      <el-table
        empty-text="暂无数据"
        :data="state.tableData"
        :header-cell-style="elTableStyle.headerCellStyle"
        border
        height="100%">
        <el-table-column v-for="item of state.tableHeader" :label="item.label" :prop="item.prop" :key="item.label" align="center">
          <template #default="scope">
            <span v-if="item.prop === 'status'">{{!scope.row[item.prop] ? '正常' : '冻结'}}</span>
            <span v-else>{{scope.row[item.prop] || '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <div class="operation">
              <div @click="handleEdit(scope.row)">
                <el-icon>
                  <Edit />
                </el-icon>
                <p>编辑</p>
              </div>
              <div class="freezed" @click="handleFreezed(scope.row)">
                <el-icon>
                  <Lock v-if="!scope.row.status" />
                  <Unlock v-else />
                </el-icon>
                <p>{{!scope.row.status ? '冻结' : '解冻'}}</p>
              </div>
              <div @click="handleDelete(scope.row)">
                <el-icon>
                  <Delete />
                </el-icon>
                <p>删除</p>
              </div>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-config-provider :locale="customPagination">
        <el-pagination
          background
          @current-change="handleCurrentChange"
          :current-page="state.currentPage"
          :page-size="20"
          layout="total, prev, pager, next, jumper"
          :total="state.tableData.length">
        </el-pagination>      
      </el-config-provider>
    </div>

    <el-dialog
      title="用户管理"
      v-model="state.dialogVisible"
      width="400px"
      :before-close="handleClose">
      <div class="my-form-item">
        <span>用户名</span>
        <el-input v-model="state.formList.username" placeholder="请输入用户名"></el-input>
      </div>
      <div class="my-form-item">
        <span>邮箱</span>
        <el-input v-model="state.formList.email" placeholder="请输入用户名"></el-input>
      </div>
      <div class="my-form-item">
        <span>用户角色</span>
        <el-select v-model="state.formList.role" placeholder="请选择角色">
          <el-option
            v-for="item in state.roleOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </div>
      <div v-if="!state.formList.id" class="my-form-item">
        <span>密码</span>
        <el-input type="password" v-model="state.formList.password" placeholder="请输入密码"></el-input>
      </div>
      <div v-if="state.formList.id" class="my-form-item">
        <el-button type="danger" @click="state.passwordDialog = true">修改密码</el-button>
      </div>
      <div class="dialog-footer">
        <el-button type="primary" @click="confirm">确 定</el-button>
        <el-button @click="clearForm();state.dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="修改密码"
      v-model="state.passwordDialog"
      width="400px"
      :before-close="handleClose">
        <div class="my-form-item">
          <el-input type="password" v-model="state.password" placeholder="请输入新密码"></el-input>
        </div>
        <div class="my-form-item">
          <el-input type="password" v-model="state.rePassword" placeholder="请输入再次新密码"></el-input>
        </div>
      <div class="dialog-footer">
        <el-button type="primary" @click="edidPassword">确 定</el-button>
        <el-button @click="clearPassword();state.passwordDialog = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { Search, Plus, Edit, Delete, Lock, Unlock } from "@element-plus/icons-vue";
import elTableStyle from "../../../config/third-plugins/element/elTable";
import customPagination from "../../../config/third-plugins/customPagination";

interface um {
  searchValue:string,

  tableData:Array<any>,
  tableHeader:Array<any>,
  currentPage:number,

  dialogVisible:boolean,
  formList:any,
  roleOptions:Array<any>,
  passwordDialog:boolean,

  password:string,
  rePassword:string
}

const state = reactive<um>({
  searchValue: '',
  tableData: [],
  tableHeader: [
    { label: '用户名', prop: 'username' },
    { label: '邮箱', prop: 'email' },
    { label: '角色', prop: 'roleName' },
    { label: '状态', prop: 'status' }
  ],

  currentPage: 1,

  dialogVisible: false,

  formList: {
    username: '',
    email: '',
    role: '',
    password: ''
  },
  roleOptions: [
    {
      label: 'Authenticated',
      value: 1
    },
    {
      label: 'Public',
      value: 2
    }
  ],
  passwordDialog: false,

  password: '',
  rePassword: ''
})

const handleAdd = () => {
  clearForm()
  state.dialogVisible = true
}

const searchData = () => {}

const handleEdit = (data:any) => {
  state.formList = JSON.parse(JSON.stringify(data))
  state.dialogVisible = true
}

const handleFreezed = (data:any) => {
  $ajax.put(`/api/users/${data.id}`, {
    blocked: !data.status
  }).then(() => {
    data.status = !data.status
    ElMessage({
      type: 'success',
      message: '修改成功'
    })
    getTableData()
    state.dialogVisible = false
  }).catch(() => {
    ElMessage({
      type: 'error',
      message: '修改失败'
    })
  })
}

const handleDelete = (data:any) => {
  ElMessageBox.confirm(
    '此操作将永久删除该用户，是否继续？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    $ajax.del(`/api/users/${data.id}`).then(res => {
      getTableData()
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '删除失败'
      })
    })
  })
}

const handleCurrentChange = (val:any) => {}

const handleClose = (done:any) => {
  done()
  clearPassword()
  clearForm()
}

const confirm = () => {
  if (!state.formList.id) {
    $ajax.post('user', {
      username: state.formList.username,
      role: state.formList.role,
      password: state.formList.password,
      email: state.formList.email,
      blocked: false,
      confirmed: true
    }).then(res => {
      ElMessage({
        type: 'success',
        message: '添加成功'
      })
      getTableData()
      state.dialogVisible = false
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '添加失败'
      })
    })
  } else {
    $ajax.put(`/api/users/${state.formList.id}`, {
      username: state.formList.username,
      email: state.formList.email,
      role: state.formList.role
    }).then(() => {
      ElMessage({
        type: 'success',
        message: '编辑成功'
      })
      getTableData()
      state.dialogVisible = false
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '编辑失败'
      })
    })
  }
}

const edidPassword = () => {
  if (state.password === state.rePassword) {
    $ajax.put(`/api/users/${state.formList.id}`, {
      password: state.password
    }).then(() => {
      ElMessage({
        type: 'success',
        message: '修改成功'
      })
      getTableData()
      state.passwordDialog = false
      clearPassword()
    }).catch(() => {
      ElMessage({
        type: 'error',
        message: '修改失败'
      })
    })
  } else {
    ElMessage({
      type: 'warning',
      message: '密码两次输入不一致'
    })
  }
}

const clearForm = () => {
  state.formList = {
    username: '',
    email: '',
    role: '',
    password: ''
  }
}

const clearPassword = () => {
  state.password = ''
  state.rePassword = ''
}

const getTableData = () => {
  $ajax.get('user', {
    'pagination[page]': state.currentPage,
    'pagination[pageSize]': 10,
    populate: '*'
  }).then(res => {
    if (res) {
      state.tableData = res.map((i:any) => {
        return {
          id: i.id,
          username: i.username,
          email: i.email,
          roleName: i.role.name,
          roleType: i.role.type,
          role: i.role.id,
          status: i.blocked
        }
      })
    }
  })
}

onMounted(() => {
  getTableData()
})
</script>

<style scoped lang="scss">
.user-manager {
  height: 100%;
  position: relative;
  display: flex;
  flex-direction: column;
  .search {
    display: flex;
    margin-bottom: 15px;
    :deep(.el-input) {
      width: 400px;
      margin-right: 10px;
    }
  }

  .table-con {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .operation {
      display: flex;
      justify-content: center;
      div {
        color: #409eff;
        margin-right: 10px;
        cursor: pointer;
        display: flex;
        align-items: center;
        p {
          position: relative;
          top: 1px;
          left: 2px;
        }
      }
      .freezed {
        i::before {
          position: relative;
          left: 7px;
        }
      }
    }
  }

  .userDescribe {
    border: 1px solid #d8d8d8;
    padding: 1rem 1rem 2rem;
    margin-top: 1rem;
    color: #666;
    > p {
      font-weight: bold;
    }
    > div {
      font-size: .8rem;
      > div {
        display: flex;
        > span:first-of-type {
          display: block;
        }
      }
    }
  }

  .my-form-item {
    display: flex;
    span {
      line-height: 32px;
      display: inline-block;
      margin-right: 10px;
      width: 70px;
      text-align-last: justify;
    }
    margin-bottom: 17px;
    :deep(.el-input) {
      flex: 1;
    }
    :deep(.el-select) {
      flex: 1;
    }
  }

  :deep(.el-pagination){
    align-self: end;
    margin: 15px 0 15px 0;
  }
  :deep(.el-dialog__body) {
    padding: 5px 30px 30px 30px;
  }
  .dialog-footer {
    text-align: right;
    margin-top: 20px;
  }

  :deep(.el-table th.el-table__cell) {
    .cell {
      border-right: 1px solid #ccc;
    }
  }
  :deep(.el-table th.el-table__cell:nth-last-child(1)) {
    .cell {
      border-right: none;
    }
  }
  :deep(.el-table--border) {
    border: none;
  }
  :deep(.el-table--border .el-table__cell) {
    border: none;
    border-bottom: 1px solid #ebeef5;
  }
  :deep(.el-table--border::after) {
    background-color: #fff;
  }

  :deep(.el-table__border-left-patch) {
    background-color: #fff;
  }
}
</style>